package com.m1905hd.user.web.controller

import com.m1905hd.common.global.JSONCode
import com.m1905hd.common.util.Page
import com.m1905hd.user.entity.Role
import com.m1905hd.user.entity.User
import com.m1905hd.user.service.RoleService
import com.m1905hd.user.service.UserService
import com.m1905hd.user.utils.PasswordHelper
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authz.annotation.RequiresPermissions
import org.apache.shiro.authz.annotation.RequiresUser
import org.apache.shiro.subject.Subject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam

import javax.servlet.http.HttpServletRequest

/**
 *
 * @author weiwei.huang
 * @email ihuangweiwei@163.com
 * @date 15/3/30
 */
@Controller
@RequestMapping("user")
class UserController {


    @Autowired
    UserService userService

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("user:view")
    def showList() {
        return "user/list"
    }


    @RequestMapping(value = "/list.json")
    @RequiresPermissions("user:view")
    def list(
            @RequestParam(defaultValue = "0") int start,
            @RequestParam(defaultValue = "20") int limit,
            @RequestParam(defaultValue = "1") int pageIndex, String name, String realName,
            @RequestParam(defaultValue = "-1") int available) {
        Page page = userService.list([userName: name, realName: realName, available: available], pageIndex, limit)
        [results: page.count, rows: page.data]
    }


    static final String DEFAULT_PASSWORD = "hd123456"

    @RequestMapping(value = "/edit.json")
    @RequiresPermissions("user:edit")
    def create(
            @RequestParam(defaultValue = "0") int id, String userName, String realName, String email,
            @RequestParam(defaultValue = "false") boolean isNew) {
        User user = new User(userName, realName, email)
        user.setId(id)
        if (isNew) {
            PasswordHelper.HashPassword hashPassword = PasswordHelper.encryptPassword(DEFAULT_PASSWORD)
            user.salt = hashPassword.salt
            user.password = hashPassword.password
            this.userService.create(user)
        } else {
            this.userService.update(user)
        }
        [code: JSONCode.SUCCESS.code]
    }


    @RequestMapping(value = "/delete.json", method = RequestMethod.POST)
    @RequiresPermissions("user:edit")
    def delete(String ids) {
        String[] idsList = ids.split(",")
        idsList.each {
            this.userService.delete(Integer.valueOf(it))
        }
        [code: JSONCode.SUCCESS.code]
    }


    @RequestMapping(value = "changeStatus/{id}.json")
    @RequiresPermissions("user:edit")
    def changeStatus(@PathVariable("id") int id) {
        User user = this.userService.find(id)
        int available = user.available == 1 ? 0 : 1
        this.userService.changeStatus(id, available) ? [code: JSONCode.SUCCESS.code] : [code: JSONCode.ERROR.code]
    }


    @RequestMapping(value = "resetPassword/{id}.json")
    @RequiresPermissions("user:edit")
    def resetPassword(@PathVariable("id") int id) {
        this.userService.resetPassword(id, DEFAULT_PASSWORD) ? [code: JSONCode.SUCCESS.code] : [code: JSONCode.ERROR.code]
    }


    @RequestMapping(value = "password", method = RequestMethod.GET)
    @RequiresUser
    def password() {
        return "user/password"
    }


    @RequestMapping(value = "password", method = RequestMethod.POST)
    @RequiresUser
    def passwordM(String oldPassword, String password, Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        def principalCollection = currentUser.getPrincipals()
        String username = (String) principalCollection.getPrimaryPrincipal();
        User user = this.userService.findByUserName(username)
        String oPassword = user.password
        String salt = user.salt

        String pp = PasswordHelper.encryptPassword(oldPassword, salt)
        String msg = "跟原始密码不匹配"
        if (pp.equals(oPassword)) {
            if (this.userService.resetPassword(user.id, password)) {
                msg = "密码修改成功"
            } else {
                msg = "密码修改失败"
            }
        }
        model.addAttribute("msg", msg)
        return "user/password"

    }

    @Autowired
    RoleService roleService


    @RequestMapping(value = "role/{id}", method = RequestMethod.GET)
    @RequiresPermissions("user:edit")
    def role(@PathVariable int id, Model model) {
        User user = this.userService.find(id)
        List<Integer> roleIds = user.getRoleIds()
        List<Role> roleList = this.roleService.findAll()
        model.addAttribute("roleIds", roleIds)
        model.addAttribute("roleList", roleList)
        model.addAttribute("id", id)
        return "user/role"
    }

    @RequestMapping(value = "/role/{id}", method = RequestMethod.POST)
    @RequiresPermissions("user:edit")
    def roleM(@PathVariable int id, HttpServletRequest request) {
        def roleIds = request.getParameterValues("roleIds")
        roleIds = roleIds.toString().replaceAll("\\[|\\]", "").replaceAll(" ", "")
        this.userService.updateRoles(id, roleIds)
        return "redirect:/user/role/${id}".toString()
    }

    //email模块
//
//    @Autowired
//    EmailService emailService
//
//    @RequestMapping(value = "/email/delete", method = RequestMethod.POST)
//    def emailDel(String ids){
//        String[] idsList = ids.split(",")
//        idsList.each {
//            this.emailService.delEmailUser(Integer.valueOf(it))
//        }
//    }
//
//    @RequestMapping(value = "/email/add", method = RequestMethod.POST)
//    def emailAdd(List<String> userNames){
//
//        userNames.each {
//            this.emailService.addEmailUser(it)
//        }
//    }
//
//    @RequestMapping(value = "/email/find", method = RequestMethod.GET)
//    def emailFind(){
//        def list = emailService.findEmailUser()
//        return new ModelAndView("user/email","userNames",list)
//    }


}
